exports.add=[{
	_type:"controller",
	_config: {
		path:"",
		name:"Forms"
	},
	send: function(config) {
		var t=this;
		var xpath=this.fields.xpath;
		var form=this.site.models.Form.List("get_by_code",{code:this.fields.form_code})[0];
		if (!form) {
			return JSON.stringify({error:"No form exists"});
		}
		var errors={};
		var flag=false;
		form.fields_not_null.split(/\s*\n\s*/).forEach(function(fld) {
			if (fld.length==0) return;
			if (!t.fields[fld] || t.fields[fld].length==0) {errors[fld]=t.F("Views","L","controllers/Forms","Field is empty",1);flag=true;}
		});
		if (flag) {
			return JSON.stringify({call:form.func_error,errors:errors,xpath:xpath});
		}
		var files;
		if (this.req.files) {
			for (var k in this.req.files) {
				var f=this.req.files[k];
				if (!files) files=[];
				var mime=this.F("Files","guess_mime",f.originalName.match(/\.(\w+)$/)[1]);
				files.push({data:f.data,filename:f.originalName,"Content-Type":mime});
			}
		}
//		if (files) throw files;
		for (var i=1;i<3;i++) {
			if (!form["mail_template"+i+"_id"]) continue;
			var mt=this.site.models.MailTemplate.Get(form["mail_template"+i+"_id"]);
			this.F("Functions","send_mail",mt.code,false,files);
		}
		
		var r = {call:form.func_ok};
		if (t.fields.send_fields) r.fields = t.fields;
			
		return JSON.stringify(r);
	}
}];
